﻿using System;
using System.Threading;
using System.Globalization;
namespace Trackr.GUI.Extensions
{
	public static class ExtensionMethods
	{
		/// <summary>
		/// Gets the week for the current value of this instance
		/// </summary>
		/// <param name="dateTime"></param>
		/// <returns>a week number</returns>
		public static int GetWeek(this DateTime dateTime)
		{
			return CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dateTime, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
		}
		/// <summary>
		/// Gets the firts day of the the given week
		/// </summary>
		/// <param name="weekNr"></param>
		/// <param name="year"></param>
		/// <returns></returns>
		public static DateTime GetWeekStartDate(this int weekNr, int? year)
		{
			if (year == null)
				year = DateTime.Now.Year;
			DateTime jan1 = new DateTime(year.Value, 1, 1);

			int daysOffset = DayOfWeek.Monday - jan1.DayOfWeek;
			DateTime firstMonday = jan1.AddDays(daysOffset);
			var rule = System.Globalization.CalendarWeekRule.FirstFourDayWeek;
			var cal = CultureInfo.CurrentCulture.Calendar;
			int firstWeek = cal.GetWeekOfYear(firstMonday, rule, DayOfWeek.Monday);

			//if (firstWeek <= 1)
			//{
			//    weekNr -= 1;
			//}
			weekNr -= 1;
			DateTime result = firstMonday.AddDays(weekNr * 7);
			return result;
		}
		/// <summary>
		/// Will try to parse a value or return a default value
		/// </summary>
		/// <param name="input">the input string to try to parse</param>
		/// <param name="defaultVal">the default value to return if the parsing fails</param>
		/// <returns>an int</returns>
		public static T ParseDefault<T>(this string input, T defaultVal)
		{
			if (string.IsNullOrEmpty(input))
				return defaultVal;
			try
			{
				var converted = Convert.ChangeType(input, typeof(T));
				return (T)converted;
			}
			catch
			{
				return defaultVal;
			}
		}
	}
}
